<template>
  <view class="confirm-order-container">
    <!-- 收货地址区域 -->
    <view class="shipping-address-section">
      <view class="section-title">收货地址</view>
      <view class="address-info" @click="selectAddress">
        <text class="address">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}</text>
        <text class="contact">{{ selectedAddress.name }}  {{ selectedAddress.phone }}</text>
      </view>
    </view>
    
    <!-- 商品列表区域 -->
    <view class="product-list-section">
      <view class="store-name">{{ storeName }}</view>
      <view v-for="(product, index) in products" :key="index" class="product-item">
        <view class="product-left">
          <image :src="product.imgUrl" class="product-img"></image>
          <text class="product-desc">{{ product.name }}  {{ product.specification }}</text>
        </view>
        <text class="product-price">￥{{ product.price }} x {{ product.quantity }}</text>
        <text class="product-total">￥{{ (product.price * product.quantity).toFixed(2) }}</text>
      </view>
      
      <!-- 订单时间显示 -->
      <view class="order-time-section">
        <text class="order-time">订单时间: {{ orderTime }}</text>
      </view>
    </view>
    
    <!-- 底部金额和提交按钮区域 -->
    <view class="footer">
      <!-- 修改这里，使用计算属性 totalAmountComputed -->
      <text class="total-amount">实付金额 ￥{{ totalAmountComputed.toFixed(2) }}</text>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 选中的地址
      selectedAddress: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: ''
      },
      // 店铺名称
      storeName: '',
      // 商品列表
      products: [],
      // 移除totalAmount，因为使用计算属性替代
      // 订单时间
      orderTime: ''
    };
  },
  computed: {
    // 计算订单总金额
    totalAmountComputed() {
      return this.products.reduce((total, product) => {
        return total + product.price * product.quantity;
      }, 0);
    }
  },
  onLoad(options) {
    // 初始化订单时间
    this.formatOrderTime();
    
    // 加载商品数据
    if (options.products) {
      const products = JSON.parse(options.products);
      this.products = products;
      this.storeName = products.length > 0 ? products[0].shopName : '';
    }
    
    // 加载默认地址
    this.loadDefaultAddress();
  },
  onShow() {
    // 监听地址选择事件
    uni.$on('addressSelected', (address) => {
      this.selectedAddress = address;
    });
    
    // 或者从本地存储获取选择的地址
    const selectedAddress = uni.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.selectedAddress = selectedAddress;
      uni.removeStorageSync('selectedAddress');
    }
  },
  onUnload() {
    // 移除事件监听
    uni.$off('addressSelected');
  },
  methods: {
    // 格式化订单时间
    formatOrderTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      
      this.orderTime = `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 加载默认地址
    loadDefaultAddress() {
      const addressList = uni.getStorageSync('addressList') || [];
      if (addressList.length > 0) {
        // 优先使用默认地址，没有则使用第一个地址
        const defaultAddress = addressList.find(item => item.isDefault) || addressList[0];
        this.selectedAddress = {...defaultAddress};
      } else {
        // 没有地址时使用默认值
        this.selectedAddress = {
          name: '张三',
          phone: '13800000000',
          province: '浙江省',
          city: '杭州市',
          district: '西湖区',
          detailAddress: '文三路100号'
        };
      }
    },
    // 选择地址
    selectAddress() {
       // 保存当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      uni.setStorageSync('returnPage', currentPage.route);
      // 存储当前页面路径，以便返回时识别
      uni.setStorageSync('returnPage', 'confirmOrder');
     // 使用绝对路径跳转
      uni.navigateTo({
        url: "/pages/addressEdit/addressEdit?from=confirm"
      });
    },
    // 提交订单
    submitOrder() {
      if (!this.selectedAddress.name) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return;
      }
      
      const orderInfo = {
        storeName: this.storeName,
        orderTime: this.orderTime,
        products: this.products,
        // 修改这里，使用计算属性 totalAmountComputed
        totalAmount: this.totalAmountComputed,
        address: this.selectedAddress
      };

      // 保存订单
      const allOrders = uni.getStorageSync('allOrders') || [];
      allOrders.push(orderInfo);
      uni.setStorageSync('allOrders', allOrders);

      uni.showModal({
        title: '确认订单',
        content: '确认提交订单吗？',
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/payment/payment?totalAmount=${this.totalAmountComputed}`
            });
          }
        }
      });
    }
  }
};
</script>

<style>
.confirm-order-container {
  background-color: #f5f5f5;
  padding: 15px;
  padding-bottom: 60px;
}

.shipping-address-section {
  background-color: white;
  border-radius: 5px;
  margin-bottom: 15px;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.address-info {
  cursor: pointer;
}

.address {
  font-size: 14px;
  color: #333;
  display: block;
  margin-bottom: 5px;
}

.contact {
  font-size: 12px;
  color: #666;
}

.product-list-section {
  background-color: white;
  border-radius: 5px;
  margin-bottom: 15px;
  padding: 15px;
}

.store-name {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eaeaea;
}

.product-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-img {
  width: 60px;
  height: 60px;
  border-radius: 3px;
  margin-right: 10px;
}

.product-desc {
  font-size: 14px;
  color: #333;
}

.product-price {
  font-size: 14px;
  color: #FF5722;
  margin: 0 10px;
}

.product-total {
  font-size: 14px;
  color: #FF5722;
  min-width: 80px;
  text-align: right;
}

.order-time-section {
  padding: 10px 0;
  margin-top: 10px;
  border-top: 1px solid #eaeaea;
  text-align: right;
}

.order-time {
  font-size: 14px;
  color: #666;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 10px 15px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.total-amount {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.submit-btn {
  background-color: #1E90FF;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  margin-right: 30px;
  border: none;
}
</style>